import base64
import datetime
import json
import mimetypes
import subprocess
from io import BytesIO

import xlsxwriter as xlsxwriter
from flask import Blueprint, render_template, request, redirect, url_for, make_response, session, jsonify, current_app
from flask import flash
from flask_security import logout_user, login_required, SQLAlchemyUserDatastore, roles_required,login_user, current_user
import os

from .files import make_zip
from .readExcel import Excelcheck
from .. import db

# 2020年9月4日 17:05:02  puamac<3162289690@qq.com>
import socket

def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

def get_remote_addr():
    """获取客户端IP地址"""
    address = request.headers.get('X-Forwarded-For', request.remote_addr)
    if not address:
        address = address.encode('utf-8').split(b',')[0].strip()
    return address



def down(source_dir):
    if source_dir == 'all':
        source_dir = current_app.config.get('UPLOADPATH')
        filename = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        output_filename = 'upload_{}.zip'.format(filename)
    else:
        source_dir = base64.b64decode(source_dir).decode("utf-8")
        filename = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        output_filename = '{}_{}.zip'.format(os.path.basename(source_dir).split('.')[0],filename)
    current_app.logger.info("下载目录 [{}],用户 {}".format(filename,'task'));
    # th2mail(current_user.username, source_dir, source_dir,None)
    f = BytesIO()
    make_zip(source_dir, f)
    f.seek(0)
    fp = f.getvalue()
    response = make_response(fp)
    mime_type = mimetypes.guess_type(output_filename)[0]
    response.headers['Conten-type'] = mime_type
    response.headers["Content-Disposition"] = "attachment; filename={}".format(output_filename.encode().decode('latin-1'))
    return response


# 读excel   puamac <3162289690@qq.com>   2020年11月1日 23:39:31
def read_excel(filepath='model/moban/for_2019_ldzy.xlsx'):
    ex = Excelcheck(file=filepath).to_json()
    # print(ex)
    return ex


def listdirs(path=None,type=None):
    if path is None:
        path = 'edomlist'
    if type is None:
        path = 'edom'
    files = os.listdir(path)
    file = []
    for f in files:
        f1 = os.path.join(path, f)
        if os.path.isdir(f1):
            files1 = listdirs(path = f1, type = type)
            file = file + files1
        else:
            if type == f:
                file.append(os.path.join(path, f))
    # print(file)
    return file

def du_php(file):
    if file is None:
        return None
    result = subprocess.check_output(['php', '-r', "include '"+file+"'; echo json_encode($text);"])
    print(result)
    return json.loads(result)

def export_file(data,sheet_name,output):
    if sheet_name is None:
        sheet_name = 'sheet1'
    if output is None:
        UPLOAD_FOLDER = current_app.config.get('UPLOAD_FOLDER' )
        addtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        filename = "app_languages-{}.xlsx".format( addtime )
        output = os.path.join( UPLOAD_FOLDER, filename)
    # 创建IO对象
    # output = BytesIO()
    # 写excel
    workbook = xlsxwriter.Workbook(output)  # 先创建一个book，直接写到io中
    sheet = workbook.add_worksheet(sheet_name)
    # {'label-max-extension': {'zh-cn': '操作失败，已分配的分机数超出了最大许可数!', 'en-us': 'The operation failed and the number of extensions assigned exceeded the maximum number of licenses!', 'spanish': 'Error, el número de extensiones asignadas supera el número de licencias'}
    header = [0] + [ v2 for v2 in [v for k, v in data.items()][0].keys()]
    keys_list = [k for k, v in data.items()]
    values_list = [v for k, v in data.items()]
    # 写入数据到A1一列
    sheet.write_row('A1', header)

    # 遍历有多少行数据
    for i in range(len(data)):
        # 遍历有多少列数据
        for x in range(len(header)):
            if header[x] == 0:
                sheet.write( i + 1, x, keys_list[i])
            else:
                if header[x] in values_list[i].keys():
                    sheet.write(i + 1, x, values_list[i][header[x]])
                else:
                    sheet.write( i + 1, x, keys_list[i] )
            # log.info('当前行：{}  当前列：{}  数据：{}'.format(str(i), str(x), data[i][key[x]]))
    workbook.close()  # 需要关闭
    # output.seek(0)  # 找到流的起始位置
    # resp = make_response(output.getvalue())
    # filename = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    # output_filename = '{}_{}.xlsx'.format(tablename, filename)
    # resp.headers["Content-Disposition"] = 'attachment; filename={}'.format(output_filename)
    # resp.headers['Content-Type'] = 'application/x-xlsx'
    # return resp




